package com.carbohydrate42.kotlin_compose_demo.compose

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.carbohydrate42.kotlin_compose_demo.util.DebugUtil


/**
 * 可参考 (包含 BLE 的 服务端和客户端, 是一个蓝牙聊天 app)
 * https://github.com/philipplackner/BluetoothChat/tree/Part3-DataTransfer
 *
 */
@SuppressLint("MissingPermission")
@Composable
@Preview(showBackground = true, showSystemUi = true)
fun TryBluetoothCommunication() {

    val context = LocalContext.current

    val bluetoothManager: BluetoothManager = context.getSystemService(BluetoothManager::class.java)
    val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter

    val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices

    val discoveredDevices = remember {
        mutableStateMapOf<String, String>()
    }

    var isBluetoothEnabled by remember {
        mutableStateOf(bluetoothAdapter?.isEnabled ?: false)
    }

    var isDeviceDiscoverable by remember {
        mutableStateOf(bluetoothAdapter?.scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
    }

    val enableBluetooth =
        rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            isBluetoothEnabled = if (it.resultCode == Activity.RESULT_OK) {
                DebugUtil.toast("Bluetooth enabled")
                true
            } else {
                DebugUtil.toast("Bluetooth not enabled")
                false
            }
        }


    val deviceDiscoverable =
        rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {

            /**
             * 参考 https://developer.android.google.cn/guide/topics/connectivity/bluetooth/find-bluetooth-devices
             *
             * A dialog is displayed, requesting the user's permission to make the device discoverable,
             * as shown in figure 2. If the user responds "Allow," then the device becomes discoverable
             * for the specified amount of time. Your activity then receives a call to the onActivityResult() callback,
             * with the result code equal to the duration that the device is discoverable.
             * If the user responded "Deny", or if an error occurred, the result code is RESULT_CANCELED.
             */
            isDeviceDiscoverable = if (it.resultCode != Activity.RESULT_CANCELED) {
                DebugUtil.toast("Device discoverable")
                true
            } else {
                DebugUtil.toast("Device not discoverable")
                false
            }
        }

    Column {

        Text(
            text = """
            device name = ${bluetoothAdapter?.name}
            device address (假的) = ${bluetoothAdapter?.address}
            高版本android不支持mac地址的获取
            device state = ${bluetoothAdapter?.state}
            device scan mode = ${bluetoothAdapter?.scanMode}
            isBluetoothEnabled = $isBluetoothEnabled
            isDeviceDiscoverable = $isDeviceDiscoverable
        """
        )


        TextButton(
            onClick = {
                enableBluetooth.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
            }
        ) {
            Text("Enable Bluetooth")
        }

        TextButton(
            onClick = {
                pairedDevices?.forEach { device ->
                    val deviceName = device.name
                    val deviceHardwareAddress = device.address
                    DebugUtil.debugLog("Paired device: $deviceName, $deviceHardwareAddress")
                }
            }
        ) {
            Text("Show paired devices")
        }

        TextButton(onClick = {
            deviceDiscoverable.launch(
                Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
                    putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300)
                }
            )
        }) {
            Text("device is discoverable last 300 seconds")
        }

        Divider()

        Row(horizontalArrangement = Arrangement.SpaceBetween) {
            TextButton(onClick = {

                discoveredDevices.clear()

                bluetoothAdapter?.startDiscovery()

                context.registerReceiver(
                    object : BroadcastReceiver() {
                        @SuppressLint("MissingPermission")
                        override fun onReceive(context: Context, intent: Intent) {
                            when (intent.action) {
                                BluetoothDevice.ACTION_FOUND -> {
                                    // Discovery has found a device. Get the BluetoothDevice
                                    // object and its info from the Intent.
                                    val device: BluetoothDevice? =
                                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)

                                    discoveredDevices[device?.address ?: "null"] =
                                        device?.name ?: "未知设备"
                                }
                            }
                        }
                    },
                    IntentFilter(
                        BluetoothDevice.ACTION_FOUND
                    )
                )
            }) {
                Text(text = "Start discovery")
            }

            TextButton(onClick = {
                discoveredDevices.clear()

                bluetoothAdapter?.cancelDiscovery()
            }) {
                Text(text = "Cancel discovery")
            }
        }


        Column(
            modifier = Modifier
                .verticalScroll(rememberScrollState())
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            discoveredDevices.forEach { (address, name) ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            DebugUtil.toast("Connecting to $address")
                        },
                    horizontalArrangement = Arrangement.SpaceAround,

                    ) {
                    Text(text = name)
                    Text(text = address)
                }
                Divider()
            }
        }
    }
}